<template>
  <BasicForm @register="register">
    <template #img>
      <Upload
        listType="picture-card"
        :max-count="1"
        :beforeUpload="uploadImg"
        @remove="removeImg"
        v-model:file-list="fileList"
        :showUploadList="{ showPreviewIcon: false }"
        accept=".png,.jpg"
      >
        上传图片
      </Upload>
    </template>
  </BasicForm>
</template>

<script lang="ts" setup>
  /**
   * 设备配置详情表单
   * formData<{}>:表单数据
   * **/
  import { BasicForm, useForm } from '/@/components/Form';
  import { schemas } from './editDeviceFilesModel.data';
  import { ref, watch } from 'vue';
  import { Upload } from 'ant-design-vue';
  import { getOtaPackageList } from '/@/api/thingsborad/profile/deviceProfile/deviceProfile';
  import { modalFormStyleSetting } from '/@/settings/thingsBoardDesign';
  // 定义 props
  const props = defineProps({
    formData: {
      type: Object,
    },
  });
  let params = ref<Recordable>({
    pageSize: 50,
    page: 0,
    sortProperty: 'title',
    sortOrder: 'ASC',
  });
  const emit = defineEmits(['upload', 'delete-img']);
  let fileList = ref<any>([]);
  const [register, { validate, setFieldsValue, resetFields, updateSchema }] = useForm({
    layout: 'vertical',
    schemas: schemas,
    showSubmitButton: false,
    showResetButton: false,
    ...modalFormStyleSetting,
    actionColOptions: {
      span: 24,
    },
  });
  function uploadImg(file: any) {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.addEventListener('load', () => {
      emit('upload', reader.result);
    });

    return false;
  }
  function removeImg() {
    emit('delete-img');
    return true;
  }
  watch(
    () => props.formData,
    (nVal: Recordable) => {
      if (nVal.image) {
        fileList.value = [{ url: nVal.image, name: '已上传图片' }];
      }
      let paramsUrl: any =
        '/' + nVal.id.id + '/' + 'FIRMWARE?' + new URLSearchParams(params.value).toString();
      getOtaPackageList(paramsUrl)
        .then((res) => {
          let option: Recordable[] = [];
          res.data.map((data: Recordable) => {
            option.push({ label: data.tag, value: data.tag });
          });
          updateSchema({
            field: 'firmwareId',
            componentProps: {
              options: option,
            },
          });
        })
        .catch((error) => {
          console.error('获取硬件列表失败', error);
        });
      paramsUrl =
        '/' + nVal.id.id + '/' + 'SOFTWARE?' + new URLSearchParams(params.value).toString();
      getOtaPackageList(paramsUrl)
        .then((res) => {
          let option: Recordable[] = [];
          res.data.map((data: Recordable) => {
            option.push({ label: data.tag, value: data.tag });
          });
          updateSchema({
            field: 'softwareId',
            componentProps: {
              options: option,
            },
          });
        })
        .catch((error) => {
          console.error('获取软件列表失败', error);
        });
      if (nVal.defaultDashboardId != null) {
        nVal.defaultDashboardId = JSON.stringify(nVal.defaultDashboardId);
      }
      if (nVal.defaultRuleChainId != null) {
        nVal.defaultRuleChainId = JSON.stringify(nVal.defaultRuleChainId);
      }
      if (nVal.defaultEdgeRuleChainId != null) {
        nVal.defaultEdgeRuleChainId = JSON.stringify(nVal.defaultEdgeRuleChainId);
      }
      setFieldsValue(nVal);
    },
  );

  defineExpose({
    validate,
    resetFields,
  });
</script>
